package com.android.mangalib.activity;

import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.xml.sax.SAXException;

import com.android.mangalib.adapter.TomeForecastsAdapter;
import com.android.mangalib.activity.R;
import com.android.mangalib.constant.Constant;
import com.android.mangalib.object.Tome;
import com.android.mangalib.parser.XMLParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * This activity is called when the user click on the "forecast" button in the main view
 */
public class ForecastActivity extends Activity {
	
	ListView tomeForecastsListView;
	List<Tome> bookList;
	TextView monthPriceTextView;
	
	// This 2 variables will store the value of month and year of the spinner when one of the spinner value changed.
	// The other value will stay the same
	int tempMonth, tempYear; 
	
	TomeForecastsAdapter tomeAdapter;
	
	Spinner months_spinner, years_spinner;
	
	@Override
	/**
	 * Main method, called when the activity is created
	 */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forecasts);
        
        // Disable the "previous" button and remove the logo
        getActionBar().setDisplayHomeAsUpEnabled(false);
        getActionBar().setDisplayShowHomeEnabled(false);
        
        final String title = Constant.FORECAST_ACTIVITY_TITLE;
        
        setTitle(title);
        
        // Get the xml spinner for the months and set its values with the array in xml files
        months_spinner = (Spinner)findViewById(R.id.dateSpinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.months, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        months_spinner.setAdapter(adapter);
        
        // Set the selected item with the current month
        months_spinner.setSelection(Calendar.getInstance().get(Calendar.MONTH));
        
        // Add the listener for the months spinners which will change the list when modified
        months_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onNothingSelected(AdapterView<?> parent) {
            }
            
            
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				try {
					// Update the list of book and the total price when months spinner is modified
					updateBookList(position, 0);
					updateMonthPrice();
				} catch (Exception e) {
					Log.v("ERROR", e.getMessage());
			//		e.printStackTrace();
				}
			}
        });
        
        
        // Get the xml spinner for the years and set its values with the array in xml files
        years_spinner = (Spinner)findViewById(R.id.dateYearSpinner);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.years, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        years_spinner.setAdapter(adapter2);
        
        
        // Add the listener for the years spinners which will change the list when modified
        years_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				try {
					// Update the list of book and the total price when years spinner is modified
					updateBookList(0, Integer.parseInt((String)parent.getItemAtPosition(position)));
					updateMonthPrice();
				} catch (Exception e) {
					Log.v("ERROR", e.getMessage());
			//		e.printStackTrace();
				} 
			}

			@Override
			public void onNothingSelected(AdapterView<?> view) {
				
			}
		});
        
        tomeForecastsListView = (ListView) findViewById(R.id.tomeForecastsListView);
        monthPriceTextView = (TextView) findViewById(R.id.monthPriceTextView);
        
        
	}
	
	/**
	 * Update the list of book for the selected month and year
	 * There are 2 spinners, so when one is modified, we passed 0 for the value of the other and get the temp value stored.
	 * 
	 * @param month The selected month in the spinner
	 * @param year The selected year in the spinner
	 * @throws XPathExpressionException
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 * @throws ParseException
	 */
	private void updateBookList(int month, int year) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, ParseException{
		
		/* When 0 is passed in argument, the spinner value has not changed, 
		 * the stored spinner value is the var to correctly update the view.
		 */
		if(month != 0 ){
			tempMonth = month;
		}
		if(year != 0){
			tempYear = year;
		}
		
		// Retrieve the new book list with the new month/year and recreate the view
		bookList = XMLParser.getTomeByMonths(getApplicationContext(), tempMonth, tempYear);
		tomeAdapter = new TomeForecastsAdapter(this, bookList);
		tomeForecastsListView.setAdapter(tomeAdapter);

	}
	
	/**
	 * Update the total price for the selected month and year
	 */
	private void updateMonthPrice() {

		float price = 0;
		for (Tome tome : bookList) {
			if (!tome.isOwned()) {
				price += tome.getPrice();
			}
		}
		monthPriceTextView.setText("Price : " + price + "€");
	}

}
